package com.zhengke.controller;

import com.zhengke.common.util.*;

import com.zhengke.pojo.AjaxResult;
import com.zhengke.pojo.HelpCenter;
import com.zhengke.pojo.HelpCenterTree;
import com.zhengke.service.IHelpCenterService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * *******************************
 * 项目名称：tvmall-parent
 * 文件名称：FileController
 * 类说明：  测试--电视端帮助fastdfs图片上传
 * 创建时间：2020/2/11 15:17
 *
 * @author 王鑫
 * @version 1.0
 * *******************************
 */
@Controller
@RequestMapping("fdfsHelp")
public class FileController {

    @Autowired
    IHelpCenterService ihelpService;


    /**
     * 提供跳转页面的控制层
     */
    @RequestMapping("/goToHelpCenterJsp.do")
    public String goToHelpCenterJsp() {
        return "fdfsUpload/helpCneterTree";
    }

    /**
     * 显示右侧框框的方法
     */
    @RequestMapping("/toRightJsp.do")
    public String goToRightCinterJsp(String gcId, String treeNodeName, ModelMap model, HttpServletRequest request) {
        try {
            int id = Integer.parseInt(gcId);
            //首先是根据帮助中心的id和name进行查询内容并将其传递过去
            Map<String, Object> messageMap = new HashMap<String, Object>();
            messageMap.put("help_name", treeNodeName);
            messageMap.put("help_id", id);
            HelpCenter helpCenter = ihelpService.querryHelpCenterByIdAndName(messageMap);

            model.put("helpCenter", helpCenter);
            //获取图片的路径的地址信息
            String picPath = helpCenter.getHelp_picPath();
            if (picPath == null || "".equals(picPath)) {
                model.put("gcPicPath", request.getSession().getServletContext().getRealPath("/images/") + "/noPic.png");
            } else {
                model.put("gcPicPath", helpCenter.getHelp_picPath());
            }

            int helpParentId = helpCenter.getHelp_parent_id();
            String imgW = null;
            String imgH = null;
            if (helpParentId == 0) {
                imgW = LoadProperties.findValue("imgW");
                imgH = LoadProperties.findValue("imgH");
            } else {
                imgW = LoadProperties.findValue("lunboW");
                imgH = LoadProperties.findValue("lunboH");
            }

            model.put("imgW", imgW);
            model.put("imgH", imgH);
            model.put("helpParentId", helpParentId);
            //读取config.properties查找访问路径的ip+端口
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            model.put("fileServerUrl", fileServerUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fdfsUpload/helpCenterUpd";
    }

    /**
     * 首先编写的是查询帮助中心的树的方法
     */
    @RequestMapping("/querryHelpTree.do")
    @ResponseBody
    public List<HelpCenterTree> querryHelpCenterTree(String id) {
        //首先判断传回来的help_parent_id是否是空，如果是空查询父节点
        if (id == null) {
            List<HelpCenter> helpCenterList = new ArrayList<HelpCenter>();
            //首先获取查询到的所有的帮助中心的节点的方法
            helpCenterList = ihelpService.querryHelpCenterTreeMethod("0");
            //遍历将节点信息装进返回到前台的集合中去
            List<HelpCenterTree> centerTreeList = new ArrayList<HelpCenterTree>();
            for (HelpCenter help : helpCenterList) {
                HelpCenterTree helpCenterTree = new HelpCenterTree(String.valueOf(help.getHelp_id()), help.getHelp_name(), help.getHelp_description());
                //判断是否是父级节点
                helpCenterTree.setIsParent(help.getConutChildPoint() > 0);//>0则是父级节点
                centerTreeList.add(helpCenterTree);
            }
            return centerTreeList;
        } else {
            List<HelpCenter> helpCenterList = new ArrayList<HelpCenter>();
            //首先获取查询到的所有的帮助中心的节点的方法
            helpCenterList = ihelpService.querryHelpCenterTreeMethod(id);
            //遍历将节点信息装进返回到前台的集合中去
            List<HelpCenterTree> centerTreeList = new ArrayList<HelpCenterTree>();
            for (HelpCenter help : helpCenterList) {
                HelpCenterTree helpCenterTree = new HelpCenterTree(String.valueOf(help.getHelp_id()), help.getHelp_name(), help.getHelp_description());
                //判断是否是父级节点
                helpCenterTree.setIsParent(help.getConutChildPoint() > 0);//>0则是父级节点
                centerTreeList.add(helpCenterTree);
            }
            return centerTreeList;
        }
    }


    /**
     * 添加根节点的操作
     */
    @RequestMapping("/addFatherMethod.do")
    @ResponseBody
    public AjaxResult addRootPoint() {
        try {
            //创建一个父级节点的对象
            HelpCenter helpCenter = new HelpCenter();
            helpCenter.setHelp_name("帮助中心父级节点");
            helpCenter.setHelp_parent_id(0);
            helpCenter.setHelp_sort(256);
            helpCenter.setHelp_description("添加的根节点!");
            int result = ihelpService.addFatherPointMethod(helpCenter);
            if (result > 0) {
                return new AjaxResult("200", "添加成功！！", "", helpCenter);
            } else {
                return new AjaxResult("300", "添加失败！！");
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new AjaxResult("300", "系统繁忙！！！！");
        }
    }

    /**
     * 添加子节点的操作
     */
    @RequestMapping("/addChildren.do")
    @ResponseBody
    public AjaxResult insetChildrenPointMethod(String id) {
        try {
            //转换父类的id
            int fatherId = Integer.parseInt(id);
            HelpCenter helpCenter = new HelpCenter();
            helpCenter.setHelp_name("帮助中心子级节点");
            helpCenter.setHelp_parent_id(fatherId);
            helpCenter.setHelp_sort(256);
            helpCenter.setHelp_description("添加的子节点!");
            int result = ihelpService.addFatherPointMethod(helpCenter);
            if (result > 0) {
                return new AjaxResult("200", "**添加成功**", helpCenter);
            } else {
                return new AjaxResult("300", "！！添加失败！！");
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new AjaxResult("300", "~~系统繁忙~~");
        }
    }

    /**
     * 保存节点的信息的方法
     */
    @RequestMapping("/savsPoint.do")
    @ResponseBody
    public AjaxResult savePointMethod(HttpServletRequest request, HttpServletResponse response) {
        //获取表单中的信息
        String titleName = request.getParameter("titleName");
        String helpDescription = request.getParameter("helpDescription");
        return null;
    }

    /**
     * 删除节点信息的方法
     */
    @RequestMapping("/deletePoint.do")
    @ResponseBody
    public AjaxResult deletePointMethod(String helpId) {
        //System.out.println("=====================>" + helpId);
        int result = ihelpService.delteNodePointMessageMethod(helpId);
        if (result > 0) {
            return new AjaxResult("200", "删除成功！");
        } else {
            return new AjaxResult("300", "删除失败！");
        }
    }


    /**
     * 图片的上传的接收的方法
     */
    @RequestMapping("/uploadImage.do")
    @ResponseBody
    public AjaxResult updateImage(@RequestParam("image") CommonsMultipartFile image) {
        try {
            //获取上传图片的名称
            String filePicName = image.getOriginalFilename();
            //进行上传图片的格式的判断的方法
            if (filePicName.indexOf(".jpeg") == -1
                    && filePicName.indexOf(".jpg") == -1
                    && filePicName.indexOf(".png") == -1
                    && filePicName.indexOf(".gif") == -1) {
                return new AjaxResult("300", "上传的图片的格式不正确请上传 *.png,*.jpeg,*.gif,*.jpg类型的图片");
            }
            //生成新图片的名称
            String extName = filePicName.substring(filePicName.lastIndexOf(".") + 1);
            if (image != null && !image.isEmpty()) {
                //生成新的路径
                String path = LoadProperties.findValue("imgPath") + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                //创建文件夹
                FileUtils.copyInputStreamToFile(image.getInputStream(), file);
                String rtnPath = LoadProperties.findValue("viewUrl") + "?path=" + file.getPath();

                return new AjaxResult("200", "上传成功", rtnPath, path);
            } else {
                return new AjaxResult("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }

        } catch (Exception e) {
            e.getStackTrace();
            return new AjaxResult("300", "系统异常！！");
        }
    }

    /**
     * 上传剪切后的图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/uploadCanvas.do")
    public AjaxResult updateConvars(String helpParentId, String canvasData, String delFile) {
        try {
            String path = LoadProperties.findValue("imgPath") + "/";
            String fileName = DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + ".jpg";

            File file = Base64ToImage.decodeBase64ToImage(canvasData, path, fileName);

            //删除原图片
            File delete = new File(delFile);
            if (delete != null) {
                delete.delete();
            }

            if (file != null) {
                String imgW = null;
                String imgH = null;
                if (Integer.parseInt(helpParentId) == 0) {
                    imgW = LoadProperties.findValue("imgW");
                    imgH = LoadProperties.findValue("imgH");
                } else {
                    imgW = LoadProperties.findValue("lunboW");
                    imgH = LoadProperties.findValue("lunboH");
                }
                //保存canvas转成的缩略图
                String filePath = ImageUtil.thumbnailImage(file.getPath(), Integer.parseInt(imgW), Integer.parseInt(imgH), true);
                //删除canvas原图
                file.delete();

                /*
                fastDFS操作
                 */
                //获取文件的扩展名
                String filename = fileName;
                //获取文件后缀名 从最后一个点后一位截取
                String extName = fileName.substring(filename.lastIndexOf(".") + 1);
                //上传fastDFS后图片完整地址
                String file_id = FastDfsApiOpr.upload(filePath, extName);
                //读取config.properties查找访问路径的ip+端口
                String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
                String rtPath = fileServerUrl + file_id;
                System.out.println(file_id);
                System.out.println(fileServerUrl);
                //删除剪切后的本地图片
                File delCanvas = new File(filePath);
                if (delCanvas != null) {
                    delCanvas.delete();
                }
                return new AjaxResult("200", "上传成功!", rtPath, file_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxResult("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 保存图片中的信息的方法
     */
    @RequestMapping("/saveMessageMethod.do")
    @ResponseBody
    public AjaxResult saveMessageMethod(String help_id, String titleName, String helpDescription, String gcPicpath, String fileId) {
        try {
            Map<String, Object> messageMap = new HashMap<String, Object>();
            messageMap.put("help_name", titleName);
            messageMap.put("help_id", help_id);
            messageMap.put("help_description", helpDescription);
            messageMap.put("help_picPath", gcPicpath);

            /**
             * 删除已经之前上传到服务器的图片，节省存储资源
             */
            //先判断fdfs图片服务器上原图片是否存在
            boolean isExist = false;
            String urlStr = LoadProperties.findValue("FILE_SERVER_URL") + fileId;
            try {
                URL url = new URL(urlStr);// 注：urlStr中需将空格替换为%20,否则报505
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                int state = conn.getResponseCode();
                if (state == 200) {
                    isExist = true;
                } else {
                    isExist = false;
                }
            } catch (Exception e) {
                isExist = false;
            }
            //排除修改为fdfs上传之前路径问题
            int index = fileId.indexOf("/");
            if (fileId != null && index >= 0 && isExist == true) {
                // eg:    /group1/M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                fileId = fileId.substring(1);//   group1/M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                String groupName = fileId.substring(0, fileId.indexOf("/"));//group01
                String fileName = fileId.substring(fileId.indexOf("/") + 1);///M00/00/01/rBACgF1euQiAEdrcAACbjnUEnrE193.jpg
                FastDfsApiOpr.delete(groupName, fileName);
            }

            /*
            保存修改信息
             */
            int result = ihelpService.updateNodePointMessageMethod(messageMap);
            if (result > 0) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("gcName", titleName);
                return new AjaxResult("200", "保存成功！！", "", map);
            } else {
                return new AjaxResult("300", "保存失败哦！！");
            }
        } catch (Exception e) {
            e.getStackTrace();
            return new AjaxResult("300", "系统异常！！");
        }
    }
}
